package com.hex.tcpproxy.hx;

import com.hex.tcpproxy.process.MainClient;
import com.hex.tcpproxy.util.ProxyClient;
import com.hex.tcpproxy.util.ProxyHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: [wujie]
 * @createTime: [2019/10/10 17:20]
 * @description:
 */
public class MasterClient implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(MasterClient.class);
    private Integer port;
    private String host;
    private ProxyClient proxyClient;
    private ProxyHandler proxyHandler;
    private Map<String, SalveClient> map = new ConcurrentHashMap<>();

    public MasterClient(String address) {
        String[] split = address.split(":");
        this.host = split[0];
        this.port = Integer.parseInt(split[1]);
    }

    @Override
    public void run() {
        proxyHandler = new ProxyHandler() {
            @Override
            public void read(String address, byte[] bytes) {
                DataPacket dataPacket = new DataPacket(bytes);
                String target = dataPacket.getTarget();
                if (target.startsWith("101.")) {
                    System.out.println(new String(dataPacket.getAllData()));
                }
                if (!map.containsKey(target)) {
                    SalveClient salveClient = new SalveClient(dataPacket.getOrigin(), dataPacket.getTarget(), MasterClient.this);
                    map.put(target, salveClient);
                    Thread thread = new Thread(salveClient);
                    thread.start();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if ("0.0.0.0:0".equals(dataPacket.getOrigin())) {

                } else {
                    map.get(target).writeAll(dataPacket.getRealData());
                }
            }
        };
        proxyClient = new ProxyClient(host, port, proxyHandler);
        proxyClient.connect();
    }


    public void write(String origin, String target, byte[] bytes) {
        DataPacket dataPacket = new DataPacket(origin, target, bytes);
        proxyHandler.writeAll(dataPacket.getAllData());
    }

    public void close() {
        proxyClient.close();
    }
}
